package top.easydict.handle;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.easydict.entity.Msg;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: north
 * Date:2021/12/5 21:50
 */
@ControllerAdvice
@Slf4j
public class MyExceptionHandler {
    // 捕捉shiro的异常
    @ExceptionHandler(ShiroException.class)
    public Msg handle401() {
        return Msg.noPermission().add("info", "您没有权限访问！");
    }

    // 捕捉其他所有异常
    @ExceptionHandler(Exception.class)
    public Msg globalException(HttpServletRequest request, Throwable ex) {
        return Msg.code(getStatus(request).value()).add("info", "访问出错，无法访问: " + ex.getMessage());
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }

    @ExceptionHandler
    @ResponseBody
    public Msg ErrorHandler(AuthenticationException e) {
        log.error("token认证失败！", e);
        return Msg.noPermission().add("info", "token认证失败！");
    }

    @ExceptionHandler
    @ResponseBody
    public Msg ErrorHandler(AuthorizationException e) {
        log.error("没有通过权限验证！", e);
        return Msg.noPermission().add("info", "没有通过权限验证！");
    }
}
